package net.chowda.castcluster.action.ajax;

import net.chowda.castcluster.PlayList;
import net.chowda.castcluster.VideoProvider;
import net.chowda.castcluster.playlist.PlayListManager;
import net.chowda.castcluster.util.CastClusterConfig;
import net.chowda.castcluster.util.LogUtil;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.HandlesEvent;
import net.sourceforge.stripes.action.Resolution;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.net.URLCodec;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;

/**
 * action for playlist editing actions.
 */
public class EditPlayListAction extends VideoAction {
    private static final Logger LOG = LogUtil.getLogger(EditPlayListAction.class);

    String subUrl = null;
    String playListName = null;
    String playListDescription = null;
    private static final String BASE_SOCIAL_URL = "http://localhost:8080/ccatom/cc/feeds";

    @DefaultHandler
    public Resolution addUrl() throws Exception {
        videoUrl = getVideoUrl();
        PlayListManager.addUrlToPlayList(getListId(), getVideoUrl());

        context.getRequest().setAttribute("list", PlayListManager.getPlayList(getListId()));

        context.getRequest().setAttribute("source", VideoProvider.getSourceForCCUrl(getVideoUrl()));
        return new ForwardResolution("/view/playlist_item.jsp");
    }

    @HandlesEvent("deleteUrl")
    public Resolution deleteUrl() throws Exception {
        PlayListManager.removeUrlFromPlayList(getListId(), getVideoUrl());
        context.getRequest().setAttribute("playLists", PlayListManager.getAllPlayLists());
        return new ForwardResolution("/view/playlist_select.jsp");
    }

    @HandlesEvent("addPlayList")
    public Resolution addPlayList() throws Exception {
        PlayListManager.createPlayList(getPlayListName(), getPlayListDescription());
        context.getRequest().setAttribute("playLists", PlayListManager.getAllPlayLists());
        return new ForwardResolution("/view/playlist_select.jsp");
    }

    @HandlesEvent("subPlayList")
    public Resolution subPlayList() {
        try {
            HttpClient client = new HttpClient();

            String url = BASE_SOCIAL_URL + getSubUrl();
            LOG.info("subscribing to URL: " + url);

            GetMethod method = new GetMethod(url);
            client.executeMethod(method);
            // getting response body as string should be okay here they're small.
            PlayList list = PlayListManager.xmlToPlaylist(method.getResponseBodyAsString());
            // add playlist to DOM.
            PlayListManager.createPlayList(list);

            context.getRequest().setAttribute("playLists", PlayListManager.getAllPlayLists());
        } catch (Exception e) {
            LOG.error("something bad happened whilst subscribing to: " + getSubUrl(), e);
        }
        return new ForwardResolution("/view/playlist_select.jsp");
    }

    @HandlesEvent("deletePlayList")
    public Resolution deletePlayList() throws Exception {
        PlayListManager.deletePlayList(getListId());
        context.getRequest().setAttribute("playLists", PlayListManager.getAllPlayLists());
        return new ForwardResolution("/view/playlist_select.jsp");
    }

    /**
     * I'm playing here....
     */
    @HandlesEvent("publish")
    public Resolution publish() throws Exception {
        PlayList list = PlayListManager.getPlayList(listId);
        if (list == null) throw new IllegalArgumentException("you requested an invalid feed id: " + listId);

        String baseCcUri = BASE_SOCIAL_URL;
        String username = CastClusterConfig.getInstance().getGlobalProp(CastClusterConfig.PUB_USER);
        String password = CastClusterConfig.getInstance().getGlobalProp(CastClusterConfig.PUB_PASSWORD);

        HttpClient client = new HttpClient();
        client.getParams().setAuthenticationPreemptive(true);

        PutMethod method = new PutMethod(baseCcUri+"/"+username+"/"+ new URLCodec().encode(list.getName()));
        method.setRequestEntity(new StringRequestEntity(PlayListManager.playListToXML(listId)));

//        String pair = username + ":" + password;
/*
        String header = "Basic " + new String(Base64.encodeBase64(username.getBytes())) + ":" + new String(Base64.encodeBase64(password.getBytes()));
        method.setRequestHeader("Authorization", header);

        method.setDoAuthentication(true);
        int i = client.executeMethod(method);

        System.out.println("i = " + i);
        System.out.println("method.getResponseBodyAsString() = " + method.getResponseBodyAsString());
        */
        return new ForwardResolution("/view/playlist_list.jsp");
    }

    public String getSubUrl() {
        return subUrl;
    }

    public void setSubUrl(String subUrl) {
        this.subUrl = subUrl;
    }

    public String getPlayListName() {
        return playListName;
    }

    public void setPlayListName(String playListName) {
        this.playListName = playListName;
    }

    public String getPlayListDescription() {
        return playListDescription;
    }

    public void setPlayListDescription(String playListDescription) {
        this.playListDescription = playListDescription;
    }
}
